import random
import datetime

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from payorder import models, orderser
from user.models import User
from doctor.models import doctor, Patient
from utils.alipay import AliPaySDK
from utils.authentication import JWTAuthenticationss


# Create your views here.

class CreateOrderView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def post(self, request):
        data = request.data
        print(data)
        patient = Patient.objects.filter(id=data['patient']).first()
        doc = doctor.objects.filter(id=data['doctor']).first()
        test = models.payorder.objects.filter(patient=patient, doctor=doc, status=0).first()
        if test:
            return Response({'code': 400, 'msg': '请勿重复下单', 'orderno': test.orderno})
        else:
            patient = Patient.objects.get(id=data['patient'])
            doc = doctor.objects.get(id=data['doctor'])
            user = User.objects.get(id=data['user'])
            orderno = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(10000000, 99999999))
            models.payorder.objects.create(patient=patient, doctor=doc, price=data['price'],
                                           name=data['name'], orderno=orderno, user=user, payprice=data['price'])
            return Response({'code': 200, 'msg': '下单成功', 'orderno': orderno})


class OrderDetailView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def get(self, request):
        orderno = request.query_params.get('orderno', None)
        if orderno:
            order = models.payorder.objects.filter(orderno=orderno).first()
            ser = orderser.OrderDetailSerializer(order)
            return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})
        else:
            return Response({'code': 400, 'msg': '请输入订单号'})


class CouponsView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def get(self, request):
        user = request.query_params.get('user')
        coupons = models.Coupons.objects.filter(user=user, is_show=True, num__gt=0)
        ser = orderser.CouponsSerializer(coupons, many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})


class GetPay(APIView):
    def post(self, request):
        order = request.data.get('order')
        price = request.data.get('price')
        print(order, price)
        orderlist = models.payorder.objects.filter(orderno=order, status=0).first()
        print(orderlist)
        ali = AliPaySDK()
        if not orderlist:
            return Response({'code': 400, 'msg': '订单不存在或已支付'})
        link = ali.page_pay(order, price, '支付订单-' + order)
        orderlist.status = 1
        orderlist.save()
        return Response({'code': 200, 'msg': '支付成功', 'link': link})


class UseCouponsView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def post(self, request):
        data = request.data
        if data['coupon'] != 0:
            coupon = models.Coupons.objects.filter(id=data['coupon']).first()
            print(coupon)
            if coupon.num > 0:
                order = models.payorder.objects.filter(orderno=data['order']).first()
                print(order)
                order.coupon = data['coupon']
                order.payprice = data['price']
                order.save()
                return Response({'code': 200, 'msg': '使用成功'})
            return Response({'code': 400, 'msg': '优惠券数量不足'})
        else:
            order = models.payorder.objects.filter(orderno=data['order']).first()
            order.payprice = data['price']
            order.coupon = None
            order.save()
            return Response({'code': 200, 'msg': '使用成功'})


class TestView(APIView):
    authentication_classes = [JWTAuthenticationss]

    def get(self, request):
        data = request.query_params.dict()
        print(data)
        alipay = AliPaySDK()
        success = alipay.check_sign(data)
        if success:
            orderlist = models.payorder.objects.filter(orderno=data['out_trade_no'], status=1).first()
            print(orderlist)
            # orderlist.status = 2
            # orderlist.save()
            if orderlist.coupon:
                coupon = models.Coupons.objects.filter(id=orderlist.coupon).update(num=orderlist.coupon.num - 1)
                coupon.save()
            return Response({'code': 200, 'msg': '验签成功', 'data': data})
        else:
            return Response({'code': 400, 'msg': '验签失败'})
